﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using HRProject.Code.DTO;
using System.Web.Profile;
using HRProject.Code.Common;
using System.Collections.Generic;
using HRProject.Code.DAO;

namespace HRProject.User
{
    public partial class EditUserInfo : System.Web.UI.Page
    {
        private List<BLRecordType> recordTypes;
        private List<BLRecord> records;
        private List<BLAssetPossession> assets;
        private List<string> tbxRecordStartDates;
        private List<string> tbxRecordEndDates;

        public List<BLAssetPossession> Assets
        {
            get { return assets; }
            set { assets = value; }
        }

        public List<string> TbxRecordStartDates
        {
            get { return tbxRecordStartDates; }
        }

        public List<string> TbxRecordEndDates
        {
            get { return tbxRecordEndDates; }
        }

        public List<BLRecord> Records
        {
            get { return records; }
        }

        public List<BLRecordType> RecordTypes
        {
            get { return recordTypes; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            RecordTypeDAO dao = new RecordTypeDAO();
            BLRecordType filter = new BLRecordType();
            filter.Id = Guid.Empty;
            filter.Name = string.Empty;
            recordTypes = dao.Search(filter);
            recordTypes.Insert(0,filter);

            records = new List<BLRecord>();
            assets = new List<BLAssetPossession>();
            tbxRecordStartDates = new List<string>();
            tbxRecordEndDates = new List<string>();

            Random random = new Random();

            Guid userId = Guid.Empty;
            try
            {
                userId = new Guid(Request.Params["editUserId"]);
            }
            catch (Exception exp)
            {
                Console.Write(exp.StackTrace);
            }
            MembershipUser mUser = Membership.GetUser(userId);
            if (mUser != null)
            {
                if (BLAuthentication.IsEditAllowed || (Membership.GetUser() != null && Membership.GetUser().ProviderUserKey.Equals(userId)))
                {
                    BLUser user = new BLUser(mUser);
                    if (!IsPostBack)
                    {
                        lblUserNameInfo.Text = user.UserName;
                        ckbActivate.Checked = user.IsApproved;
                        tbxEmail.Text = user.Email;
                        tbxFullName.Text = user.FullName;
                        tbxIdentifierSerial.Text = user.IdentifiedSerial;
                        tbxPhone.Text = user.Phone;
                        tbxContact.Text = user.Contact;
                        tbxAddress.Text = user.Address;
                        tbxBirthDate.Text = user.BirthDate.ToString("dd/MM/yyyy");
                        tbxBirthPlace.Text = user.BirthPlace;
                        tbxMaritalStatus.Text = user.MaritalStatus;
                        tbxPeople.Text = user.People;
                        tbxAddress2.Text = user.ExtraContact;
                        txaExtraDescription.Text = user.ExtraDescription;
                        imgIcon.ImageUrl = user.ImageUrl;
                        ddlGender.DataSource = BLGender.List;
                        ddlGender.DataValueField = "Id";
                        ddlGender.DataTextField = "Name";
                        ddlGender.DataBind();
                        ddlGender.SelectedValue = Convert.ToString(user.Gender);
                    }

                    AssetPossessionDAO assetDAO = new AssetPossessionDAO();
                    BLAssetPossession assetFilter = new BLAssetPossession();
                    assetFilter.Asset = new BLAsset();
                    assetFilter.Asset.Type = new BLAssetType();
                    assetFilter.Asset.Id = Guid.Empty;
                    assetFilter.Asset.Name = string.Empty;
                    assetFilter.Asset.Type.Id = Guid.Empty;
                    assetFilter.UserId = userId;
                    assets = assetDAO.search(assetFilter);

                    RecordDAO recordDAO = new RecordDAO();
                    BLRecord recFilter = new BLRecord();
                    recFilter.Id = Guid.Empty;
                    recFilter.Name = string.Empty;
                    recFilter.UserId = userId;
                    recFilter.Type = new BLRecordType();
                    recFilter.Id = Guid.Empty;
                    records = recordDAO.search(recFilter);

                    foreach (BLRecord r in records)
                    {
                        tbxRecordStartDates.Add("tbxRecordStartDate" + random.Next(1000, 10000));
                        tbxRecordEndDates.Add("tbxRecordEndDate" + random.Next(1000, 10000));
                    }
                }
                else
                {
                    Response.Redirect("/LogIn.aspx");
                }
            }
            else
            {
                Response.Redirect("/LogIn.aspx");
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (!BLAuthentication.IsEditAllowed)
            {
                if (Membership.GetUser() == null || !Membership.GetUser().UserName.Equals(lblUserNameInfo.Text))
                {
                    lblError.Text = ContentProvider.GetMessage("NotAuthorized");
                    return;
                }
            }
            else
            {
                if (Membership.GetUser() == null || !Membership.GetUser().UserName.Equals(lblUserNameInfo.Text))
                {
                    hplChangePassword.Visible = false;
                }
            }

            MembershipUser mUser = Membership.GetUser(lblUserNameInfo.Text);
            if (mUser != null)
            {
                BLUser user = new BLUser(mUser);
                user.IsApproved = ckbActivate.Checked;
                user.FullName = tbxFullName.Text.Trim();
                int gender;
                if (Int32.TryParse(ddlGender.SelectedValue, out gender))
                {
                    user.Gender = gender;
                }
                user.IdentifiedSerial = tbxIdentifierSerial.Text.Trim();
                user.Phone = tbxPhone.Text.Trim();
                user.Contact = tbxContact.Text.Trim();
                DateTime date = HRProject.Code.Common.Constant.DefaultMinDate;
                if (DateTime.TryParse(tbxBirthDate.Text.Trim(), out date))
                {
                    user.BirthDate = date;
                }
                user.BirthPlace = tbxBirthPlace.Text.Trim();
                user.Address = tbxAddress.Text.Trim();
                user.ExtraDescription = txaExtraDescription.Text.Trim();
                user.People = tbxPeople.Text.Trim();
                user.MaritalStatus = tbxMaritalStatus.Text.Trim();
                user.ExtraContact = tbxAddress2.Text.Trim();

                string iconUrl = string.Empty;
                if (cbxIcon.Checked && fulIcon.HasFile)
                {
                    try
                    {
                        string ext = fulIcon.PostedFile.FileName.Substring(fulIcon.PostedFile.FileName.LastIndexOf('.'));
                        iconUrl = "/image/user/" + user.UserName + ext;
                        fulIcon.PostedFile.SaveAs(Server.MapPath(iconUrl));
                        user.ImageUrl = iconUrl;
                    }
                    catch (Exception ex)
                    {
                        lblError.Text = "ERROR: " + ex.Message.ToString();
                    }
                }
                else
                {
                    lblError.Text = "You have not specified a file.";
                }

                user.SaveProfile();
                user.Email = tbxEmail.Text.Trim();

                Membership.UpdateUser(user);

                //assets
                string[] assetIds = Request.Params.GetValues("hdfAssetId");
                string[] assetStartDates = Request.Params.GetValues("tbxAssetStartDate");
                string[] assetEndDates = Request.Params.GetValues("tbxAssetEndDate");
                string[] assetDescriptions = Request.Params.GetValues("tbxAssetDescription");
                string[] assetRemovedIds = Request.Params.GetValues("hdfRemovedAssetId");
                AssetPossessionDAO assetPossessionDAO = new AssetPossessionDAO();
                if (assetRemovedIds != null)
                {
                    for (int i = 0; i < assetRemovedIds.Length; i++)
                    {
                        try
                        {
                            BLAssetPossession filter = new BLAssetPossession();
                            filter.Asset = new BLAsset();
                            filter.Asset.Id = new Guid(assetRemovedIds[i]);
                            filter.UserId = (Guid)user.ProviderUserKey;
                            filter.DataSignature = 0;
                            int result = assetPossessionDAO.delete(filter);
                        }
                        catch (Exception exp)
                        {
                            Console.Write(exp.StackTrace);
                        }
                    }
                }
                if (assetIds != null)
                {
                    for (int i = 0; i < assetIds.Length; i++)
                    {
                        try
                        {
                            BLAssetPossession filter = new BLAssetPossession();
                            filter.Asset = new BLAsset();
                            filter.Asset.Id = new Guid(assetIds[i]);
                            filter.Asset.Name = string.Empty;
                            filter.Asset.Type = new BLAssetType();
                            filter.Asset.Type.Id = Guid.Empty;
                            filter.UserId = (Guid)user.ProviderUserKey;
                            filter.Description = assetDescriptions[i];
                            filter.DataSignature = 0;
                            if (DateTime.TryParse(assetStartDates[i], out date))
                            {
                                filter.StartDate = date;
                            }
                            else
                            {
                                filter.StartDate = DateTime.Now;
                            }
                            if (DateTime.TryParse(assetEndDates[i], out date))
                            {
                                filter.EndDate = date;
                            }
                            else
                            {
                                filter.EndDate = Constant.DefaultMaxDate;
                            }
                            List<BLAssetPossession> poss = assetPossessionDAO.search(filter);
                            if (poss.Count > 0)
                            {
                                int result = assetPossessionDAO.update(filter);
                            }
                            else
                            {
                                int result = assetPossessionDAO.insert(filter);
                            }
                        }
                        catch (Exception exp)
                        {
                            Console.Write(exp.StackTrace);
                        }
                    }
                }


                //records
                string[] recordIds = Request.Params.GetValues("hdfRecordId");
                string[] pRecordTypes = Request.Params.GetValues("ddlRecord");
                string[] removedRecordIds = Request.Params.GetValues("hdfRemovedRecordId");
                string[] recordValues = Request.Params.GetValues("tbxRecordValue");
                string[] recordStarts = Request.Params.GetValues("tbxRecordStartTime");
                string[] recordEnds = Request.Params.GetValues("tbxRecordEndTime");
                string[] recordRates = Request.Params.GetValues("tbxRecordRating");
                RecordDAO recDAO = new RecordDAO();

                if (removedRecordIds != null)
                {
                    for (int i = 0; i < removedRecordIds.Length; i++)
                    {
                        try
                        {
                            BLRecord recFilter = new BLRecord();
                            recFilter.Id = new Guid(removedRecordIds[i]);
                            int result = recDAO.delete(recFilter);
                        }
                        catch (Exception exp)
                        {
                            Console.Write(exp.StackTrace);
                        }
                    }
                }

                if (pRecordTypes != null)
                {
                    for (int i = 0; i < pRecordTypes.Length; i++)
                    {
                        try
                        {
                            Guid typeId = new Guid(pRecordTypes[i]);
                            if (!typeId.Equals(Guid.Empty))
                            {
                                BLRecord record = new BLRecord();
                                record.Name = string.Empty;
                                record.Type = new BLRecordType();
                                record.Type.Id = typeId;
                                record.UserId = (Guid)user.ProviderUserKey;
                                record.Description = recordValues[i];
                                DateTime time;
                                if (DateTime.TryParse(recordStarts[i], out time))
                                {
                                    record.StartDate = time;
                                }
                                else
                                {
                                    record.StartDate = DateTime.Now;
                                }
                                if (DateTime.TryParse(recordEnds[i], out time))
                                {
                                    record.EndDate = time;
                                }
                                else
                                {
                                    record.EndDate = Constant.DefaultMaxDate;
                                }
                                byte rate;
                                if (byte.TryParse(recordRates[i], out rate))
                                {
                                    record.Rating = rate;
                                }
                                if (string.Empty.Equals(recordIds[i]))
                                {
                                    int result = recDAO.insert(record);
                                }
                                else
                                {
                                    record.Id = new Guid(recordIds[i]);
                                    int result = recDAO.update(record);
                                }
                            }
                        }
                        catch (Exception exp)
                        {
                            Console.Out.WriteLine(exp.Message);
                        }
                    }
                }
            }
            Response.Redirect(Request.RawUrl);
        }
    }
}
